var city = require('../../utils/city.js');
var amapFile = require('../../lib/amap-wx.js');

var app = getApp()
Page({
  data: {
    defaultKeyword: "输入城市名进行搜索",
    keyword: "",
    searchLetter: [],
    showLetter: "",
    winHeight: 0,
    cityList: [],
    isShowLetter: false,
    scrollTop: 0, //置顶高度
    scrollTopId: '', //置顶id
    city: "",
    hotcityList: [{
      cityCode: 110000,
      city: '北京'
    }, {
      cityCode: 310000,
      city: '上海'
    }, {
      cityCode: 440100,
      city: '广州'
    }, {
      cityCode: 440300,
      city: '深圳'
    }, {
      cityCode: 330100,
      city: '杭州'
    }, {
      cityCode: 320100,
      city: '南京'
    }, {
      cityCode: 420100,
      city: '武汉'
    }, {
      cityCode: 410100,
      city: '郑州'
    }, {
      cityCode: 120000,
      city: '天津'
    }],
    cityData: [],
    searchContext: '',
    searchResult: [],
  },
  onLoad: function(options) {
    // 生命周期函数--监听页面加载
    var searchLetter = city.searchLetter;
    var cityList = city.cityList();
    var sysInfo = wx.getSystemInfoSync();
    var winHeight = sysInfo.windowHeight;
    var itemH = winHeight / searchLetter.length;
    var tempObj = [];
    for (var i = 0; i < searchLetter.length; i++) {
      var temp = {};
      temp.name = searchLetter[i];
      temp.tHeight = i * itemH;
      temp.bHeight = (i + 1) * itemH;
      tempObj.push(temp)
    }
    this.setData({
      winHeight: winHeight,
      itemH: itemH,
      searchLetter: tempObj,
      cityList: cityList,
      city: app.globalData.currentCity
    })
  },

  //获取地理位置授权
  getUserLocation: function() {
    let vm = this;
    wx.getSetting({
      success: (res) => {
        console.log(JSON.stringify(res))
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function(res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function(dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      vm.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          vm.getLocation();
        } else {
          //调用wx.getLocation的API
          vm.getLocation();
        }
      }
    })
  },


  //获取当前位置的经纬度
  getLocation: function() {
    var that = this;
    wx.getLocation({
      type: 'wgs84', //返回可以用于wx.openLocation的经纬度
      success: function(res) {
        var latitude = res.latitude //维度
        var longitude = res.longitude //经度
        console.log(res);
        that.loadCity(latitude, longitude);
      }
    })
  },

  //把当前位置的经纬度传给高德地图，调用高德API获取当前地理位置
  loadCity: function(latitude, longitude) {
    var that = this;
    var myAmapFun = new amapFile.AMapWX({
      key: 'f0379ed3f070b760eac9542e6c1b8ae4'
    });
    myAmapFun.getRegeo({
      location: '' + longitude + ',' + latitude + '', //location的格式为'经度,纬度'
      success: function(data) {
        var cityname = data[0].regeocodeData.addressComponent.city
        if (cityname.charAt(cityname.length - 1) == '市'){
          cityname = cityname.substring(0, cityname.length - 1);
        }
        console.log(cityname)
        that.setData({
          city: cityname
          }),
          //设置全局城市地质
          app.globalData.currentCity = cityname
      },
      fail: function(info) {
        console.log(info);
      }
    })
  },

  // 搜索 及搜索结果
  searchHandle: function(e) {
    var searchContext = this.data.searchContext;
    var cityList = this.data.cityList;
    var searchArr = [];
    cityList.forEach(item => {
      var citylist = item.cityInfo;
      citylist.forEach(value => {
        if (value.city.indexOf(searchContext) >= 0) {
          searchArr.push(value);
        }
      })
    })
    if (searchArr) {
      this.setData({
        searchResult: searchArr
      })
    }
  },
  // 文本输入 事件
  searchInputCon: function(e) {
    let keywords = e.detail.value;
    this.setData({
      searchContext: keywords
    })
  },
  //选择搜索结果
  getCity: function(e) {
    this.setData({
      city: e.currentTarget.dataset.city,
      searchContext: '',
      searchResult: [],
    })
    app.globalData.currentCity = e.currentTarget.dataset.city
  },
  onReady: function() {
    // 生命周期函数--监听页面初次渲染完成

  },
  onShow: function() {
    // 生命周期函数--监听页面显示
    //关闭分享
    wx.hideShareMenu()
  },
  onHide: function() {
    // 生命周期函数--监听页面隐藏

  },
  onUnload: function() {
    // 生命周期函数--监听页面卸载

  },
  onPullDownRefresh: function() {
    // 页面相关事件处理函数--监听用户下拉动作

  },
  onReachBottom: function() {
    // 页面上拉触底事件的处理函数

  },
  clickLetter: function(e) {
    console.log(e.currentTarget.dataset)
    var showLetter = e.currentTarget.dataset.letter;
    this.setData({
      showLetter: showLetter,
      isShowLetter: true,
      scrollTopId: showLetter,
    })
    var that = this;
    setTimeout(function() {
      that.setData({
        isShowLetter: false
      })
    }, 500)
  },
  //选择城市
  bindCity: function(e) {
    console.log("bindCity");
    this.setData({
      city: e.currentTarget.dataset.city
    })
    app.globalData.currentCity = e.currentTarget.dataset.city;
    this.setData({
      scrollTop: 0
    })
  },
  //选择热门城市
  bindHotCity: function(e) {
    console.log("bindHotCity")
    this.setData({
      city: e.currentTarget.dataset.city
    })
    app.globalData.currentCity = e.currentTarget.dataset.city
  },
  //点击热门城市回到顶部
  hotCity: function() {
    this.setData({
      scrollTop: 0,
    })
  },
  bindScroll:function(e){
  
  }
})